<?php
/**
 * Dashboard is the controller for business portal.
 * 
 * LBB Solutions Oy 版权所有 © 2013
 */
class DashboardController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * Give a step guid when there is no profile, tags, default offer picture
	 */
	public function actionIndex()
	{
		//how many special views
		$sql_offers = 'SELECT SUM(reach) AS reach, SUM(notifications) AS notifications, SUM(clicks) AS clicks, SUM(redeems) AS redeems,
				MIN(local_date) AS start_date, MAX(local_date) AS end_date
			FROM tbl_merchant_special_report_day 
			WHERE id_special IN (SELECT id FROM tbl_merchant_special WHERE id_merchant=:id_merchant)';
		
		//how many customers and visits
		$sql_customers = 'SELECT COUNT(id_user) AS people, SUM(visit_times) AS visits
			FROM tbl_visit_customer_notes
			WHERE id_merchant=:id_merchant';
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_offers);
		$offers = $command->queryRow(true, array('id_merchant'=>Yii::app()->user->id));
		$command = $connection->createCommand($sql_customers);
		$customers = $command->queryRow(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
		
		if (Yii::app()->user->getState('enable_rewards') == 1) {
			$view = 'index';
		} else {
			$view = 'index_people_nearby';
		}
		$this->render($view, array(
			'offers' => $offers,
			'customers' => $customers,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function loadModel($id)
	{
		$model = MerchantForm::model()->findByPk($id);
		if ($model===null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
}